package sy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sy.listener.UsersOnlineCountListener;
import sy.model.Tinviterecord;
import sy.model.Tuser;
import sy.pageModel.*;
import sy.service.*;
import sy.service.impl.InviteServiceImpl;
import sy.util.ConfigUtil;
import sy.util.DESUtil;
import sy.util.IpUtil;
import sy.util.UserAgentUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;

/**
 * 用户控制器
 *
 * @author 孙宇
 *
 */
@Controller
@RequestMapping("/userController")
public class UserController extends BaseController {

    @Autowired
    private UserServiceI userService;

    @Autowired
    private RoleServiceI roleService;

    @Autowired
    private ResourceServiceI resourceService;

    @Autowired
    private TaskRecordServiceI taskrecordService;

    @Autowired
    private TaskTypeServiceI   taskTypeService;

    @Autowired
    private InviteServiceI inviteDao;
    /*
    在线人数获取
     */
    @RequestMapping("/online")
    public String online(HttpServletRequest request,HttpSession session) {

        ServletContext context=session.getServletContext();
        List<User> onlineUserList=(List)context.getAttribute("onlineList");
        int phone=0;
        int pc=0;
        for(User user:onlineUserList){
            if(user.getClienttype()==0){//手机端
                phone++;
            }else{//pc
                pc++;
            }
        }
        request.setAttribute("phone",phone);
        request.setAttribute("pc",pc);
        return "/online/index";
    }

    /**
     * 后台用户登录
     *
     * @param user
     *            用户对象
     * @param session
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/loginadmin")
    public String loginadmin(User user, HttpSession session, HttpServletRequest request,HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        User u = userService.loginadmin(user);
        if (u != null) {
            jsobj.put("status", "1");
            jsobj.put("msg", "sccess");
            SessionInfo sessionInfo = new SessionInfo();
            BeanUtils.copyProperties(u, sessionInfo);
            sessionInfo.setIp(IpUtil.getIpAddr(request));
            sessionInfo.setUserid(u.getUserid());
            sessionInfo.setResourceList(userService.resourceList(u.getId()));
            session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);

            //判断客户端类型
            String agent = request.getHeader("User-Agent");
            int clienttype=UserAgentUtil.getUserAgent(agent);
            u.setClienttype(clienttype);

            session.setAttribute("onlineUserBindingListener",new UsersOnlineCountListener(u));

        } else {
            jsobj.put("status", "0");
            jsobj.put("msg", "用户名或密码错误");
        }
        return jsobj.toJSONString();
    }

    /**
     * 用户登录
     *
     * @param user
     *            用户对象
     * @param session
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login(User user, HttpSession session, HttpServletRequest request,HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        User u = userService.login(user);
        if (u != null) {
            if("1".equals(u.getStatu())){
                jsobj.put("status", "1");
                SessionInfo sessionInfo = new SessionInfo();
                BeanUtils.copyProperties(u, sessionInfo);
                sessionInfo.setIp(IpUtil.getIpAddr(request));
                sessionInfo.setUserid(u.getUserid());
                sessionInfo.setResourceList(userService.resourceList(u.getId()));
                session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);
                jsobj.put("status", "1");
                //jsobj.put("msg", "/upload/Android.apk?userid="+u.getId());
                String url=getTGUrl(request,user.getUserid().intValue()+"");
                //String urlpath="promoteurl.jsp?url=dowloadController/promotedowload?dowloadpath="+downpath+"makemoney_"+userid+".apk";
                jsobj.put("msg",url==null?"":url);
                jsobj.put("tgurl","promoteurl.jsp?url="+url);
                //判断客户端类型
                String agent = request.getHeader("User-Agent");
                int clienttype=UserAgentUtil.getUserAgent(agent);
                u.setClienttype(clienttype);
                session.setAttribute("onlineUserBindingListener",new UsersOnlineCountListener(u));
            }else{
                jsobj.put("status", "0");
                jsobj.put("msg", "您帐号被禁用了");
            }

        } else {
            jsobj.put("status", "0");
            jsobj.put("msg", "用户名或密码错误");
        }
        return jsobj.toJSONString();
    }

    /**
     * 用户一键注册
     *
     * @param user
     * 			用户对象
     * @return
     */
    /**
     * @param user
     * @param session
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/regonce")
    public String regonce(User user, HttpSession session, HttpServletRequest request,HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        String str = "";
        str += (int)(Math.random()*9+1);
        for(int i = 0; i < 5; i++){
            str += (int)(Math.random()*10);
        }
        int num = Integer.parseInt(str);
        JSONObject jsobj = new JSONObject();
        User ul = new User();
        Mtaskrecord  task = new Mtaskrecord();
        try {
            Long usermax = userService.regonce();
            usermax = usermax+1;
            user.setPwd(num+"");			 //默认设置密码
            user.setName("赚客"+usermax);		 //默认设置昵称
            user.setUserid(usermax);
            Integer score = taskTypeService.gettasktype("1").getScore();
            user.setTotalscore(score);
            user.setUnchangedscore(score);
            user.setGgjnunber(1);//注册的时候送给用户一次刮奖机会
            user.setChangedscore(0);
            ul.setUserid(usermax);
            ul.setName("赚客"+usermax);
            ul.setPwd(num+"");
            ul.setGgjnunber(1);
            userService.regonce(user);
            task.setTaskType("1");
            task.setUserid(usermax);
            task.setScore(score);

            taskrecordService.add(task);
            jsobj.put("status", "1");
            jsobj.put("msg", ul);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsobj.toJSONString();
    }
    /**
     * 用户注册
     *
     * @param user
     *        用户对象
     * @return
     */
    @ResponseBody
    @RequestMapping("/reg")
    public Json reg(User user) {
        Json j = new Json();
        try {
            userService.regonce(user);
            j.setSuccess(true);
            j.setMsg("注册成功！新注册的用户没有任何权限，请让管理员赋予权限后再使用本系统！");
            j.setObj(user);
        } catch (Exception e) {
            e.printStackTrace();
            j.setMsg(e.getMessage());
        }
        return j;
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        JSONObject jsobj = new JSONObject();
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        if (session != null) {
            User u=userService.get(sessionInfo.getId());
            session.invalidate();
            // session.setAttribute("onlineUserBindingListener",new UsersOnlineCountListener(u));

        }
        jsobj.put("status", 1);
        jsobj.put("msg", "注销成功");





        return jsobj.toJSONString();
    }
    /**
     * 跳转到用户管理页面
     *
     * @return
     */
    @RequestMapping("/manager")
    public String manager() {
        return "/admin/user";
    }



    /**
     * 获取用户数据表格
     *
     * @param user
     * @return
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(User user, PageHelper ph) {
        return userService.dataGrid(user, ph);
    }

    /**
     * 跳转到添加用户页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
        User u = new User();
        u.setId(UUID.randomUUID().toString());
        request.setAttribute("user", u);
        return "/admin/userAdd";
    }

    //获取邀请记录
    @ResponseBody
    @RequestMapping("/getInviteDetail")
    public String getInviteDetail(HttpServletRequest request){

        String userid=request.getParameter("userid");

        JSONObject jsobj = new JSONObject();
        List<Tinviterecord> list=  inviteDao.getTinviterecordCount(userid);
        jsobj.put("list",list);
        String result=JSONObject.toJSONString(jsobj);
        //清除集合
        InviteServiceImpl.reulsts.clear();

        return result;


    }
    /**
     * 添加用户
     *
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Json add(User user) {
        Json j = new Json();
        try {
            userService.add(user);
            j.setSuccess(true);
            j.setMsg("添加成功！");
            j.setObj(user);
        } catch (Exception e) {
            e.printStackTrace();
            j.setMsg(e.getMessage());
        }
        return j;
    }

    //

    /*
    通过用户id查询是否存在该用户
     */
    @RequestMapping("/finduser")
    @ResponseBody
    public String finduser(HttpServletRequest request) {

        String basePath =request.getSession().getServletContext().getRealPath("/");

        String userid=request.getParameter("userid");
        JSONObject jsobj = new JSONObject();

        try {

            Tuser user=userService.getUserByUserId(userid);
            if(user!=null){

                File genapkfile=new File(basePath+"genapk");
                if(!genapkfile.exists())genapkfile.mkdir();

                //判断是否存在改推广apk 不存在就创建

                File appppathfile = new File("D:/genapk/makemoney_"+userid+".apk");

                if(!appppathfile.exists()){
                    //生成下载链接地址文件
                    Runtime rt=Runtime.getRuntime();
                    Process process= rt.exec("python D:/genapk/write.py "+userid);

                    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        System.out.println(line);
                    }
                    in.close();
                    process.waitFor();

                }

                String url=getTGUrl(request,userid);

                if(url==null){
                    jsobj.put("status", 0);
                    jsobj.put("msg", "文件不存在，请重新点击获取apk文件");
                }else{
                    jsobj.put("status", 1);
                    jsobj.put("msg", "d/p?"+url);
                    jsobj.put("tgurl","pu.jsp?url=d/p&"+url);
                }


            }else{
                jsobj.put("status", 0);
                jsobj.put("msg", "不存在用户！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            jsobj.put("status", 0);
            jsobj.put("msg", e.getMessage());

        }


        return jsobj.toJSONString();
    }

    //通过userid获得推广下载apk文件
    public  String getTGUrl(HttpServletRequest request,String userid)throws Exception{

        String basePath =request.getSession().getServletContext().getRealPath("/");
        File genapkfile=new File(basePath+"genapk");
        if(!genapkfile.exists())genapkfile.mkdir();

        File appppathfile = new File("D:/genapk/makemoney_"+userid+".apk");

        if(!appppathfile.exists()){
            return null;
        }
        String downpath="promotedowloadapp/";
        File file1 = new File(basePath+downpath);
        if(!file1.exists())file1.mkdirs();
        File out=new File(file1.getAbsolutePath()+"/makemoney_"+userid+".apk");

        //复制文件
        FileCopyUtils.copy(appppathfile,out);
        String dowloadpath=out.getAbsolutePath();
        //String urlpath="promoteurl.jsp?url=dowloadController/promotedowload?dowloadpath="+downpath+"makemoney_"+userid+".apk";
        //String urlpath="d/p?d="+userid;
        String urlpath="d="+userid;
        return urlpath;
    }
    /**
     * 跳转到用户修改页面
     *
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest request, String id) {
        User u = userService.get(id);
        u.setPwd(DESUtil.decrypt(u.getPwd()));
        request.setAttribute("user", u);
        return "/admin/userEdit";
    }

    /**
     * 修改用户-接口
     *
     * @param user
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public String edit(User user,HttpServletResponse response,HttpSession session) {
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        if(sessionInfo == null){
            jsobj.put("status", -1);
            jsobj.put("msg", "登录超时");
        }else{
            try {
                user.setId(sessionInfo.getId());
                user.setUserid(sessionInfo.getUserid());
              //判断用户是否重复绑定手机号吗和支付宝账户
            	boolean isbing=userService.jugeAcount(user);
            	if(isbing){
            		   jsobj.put("status", 0);
                       jsobj.put("msg", "该手机号码或支付宝账户已被绑定"); 
                       return jsobj.toJSONString();
            	} 
            	
                userService.edit(user);
                jsobj.put("status", 1);
                jsobj.put("msg", "sccess");
                if(user.getName()!=null && user.getPhonenumber()!=null && user.getQq()!=null && user.getAlipay()!= null &&  !("").equals(user.getName()) && !("").equals(user.getPhonenumber()) && !("").equals(user.getQq()) && !("").equals(user.getAlipay())){
                    if(taskrecordService.checklevlws(sessionInfo.getUserid()) == 0){
                        updatetaskcount(sessionInfo.getId());	//更新记录
                        addtaskrecord(sessionInfo.getUserid()); //增加任务记录
                        Integer score = taskTypeService.gettasktype("2").getScore();
                        this.updatetotalscore(sessionInfo.getId(),score, 1);//更新积分
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                jsobj.put("status", 0);
                jsobj.put("msg", "更新失败");
            }
        }
        return jsobj.toJSONString();
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/editadmin")
    @ResponseBody
    public Json editadmin(User user) {
        Json j = new Json();
        try {
            user.setPwd(DESUtil.encrypt(user.getPwd()));
            userService.editadmin(user);
            j.setSuccess(true);
            j.setMsg("编辑成功！");
            j.setObj(user);
        } catch (Exception e) {
            // e.printStackTrace();
            j.setMsg(e.getMessage());
        }
        return j;
    }


    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Json delete(String id, HttpSession session) {
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        Json j = new Json();
        if (id != null && !id.equalsIgnoreCase(sessionInfo.getId())) {// 不能删除自己
            userService.delete(id);
        }
        j.setMsg("删除成功！");
        j.setSuccess(true);
        return j;
    }

    /**
     * 修改禁用启用
     *
     * @param id
     * @return
     */
    @RequestMapping("/updatestatu")
    @ResponseBody
    public Json updatestatu(String id,String statu) {
        User u = userService.get(id);
        u.setStatu(statu);
        Json j = new Json();
        try {
            userService.editstatu(u);
        } catch (Exception e) {
            e.printStackTrace();
        }
        j.setMsg("更改成功！");
        j.setSuccess(true);
        return j;
    }
    /**
     * 批量删除用户
     *
     * @param ids
     *            ('0','1','2')
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    public Json batchDelete(String ids, HttpSession session) {
        Json j = new Json();
        if (ids != null && ids.length() > 0) {
            for (String id : ids.split(",")) {
                if (id != null) {
                    this.delete(id, session);
                }
            }
        }
        j.setMsg("批量删除成功！");
        j.setSuccess(true);
        return j;
    }

    /**
     * 跳转到用户授权页面
     *
     * @return
     */
    @RequestMapping("/grantPage")
    public String grantPage(String ids, HttpServletRequest request) {
        request.setAttribute("ids", ids);
        if (ids != null && !ids.equalsIgnoreCase("") && ids.indexOf(",") == -1) {
            User u = userService.get(ids);
            request.setAttribute("user", u);
        }
        return "/admin/userGrant";
    }

    /**
     * 用户授权
     *
     * @param ids
     * @return
     */
    @RequestMapping("/grant")
    @ResponseBody
    public Json grant(String ids, User user) {
        Json j = new Json();
        userService.grant(ids, user);
        j.setSuccess(true);
        j.setMsg("授权成功！");
        return j;
    }

    /**
     * 跳转到编辑用户密码页面
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/editPwdPage")
    public String editPwdPage(String id, HttpServletRequest request) {
        User u = userService.get(id);
        request.setAttribute("user", u);
        return "/admin/userEditPwd";
    }

    /**
     * 编辑用户密码
     *
     * @param user
     * @return
     */
    @RequestMapping("/editPwd")
    @ResponseBody
    public Json editPwd(User user) {
        Json j = new Json();
        userService.editPwd(user);
        j.setSuccess(true);
        j.setMsg("编辑成功！");
        return j;
    }

    /**
     * 跳转到编辑自己的密码页面
     *
     * @return
     */
    @RequestMapping("/editCurrentUserPwdPage")
    public String editCurrentUserPwdPage() {
        return "/user/userEditPwd";
    }
    /**
     * 修改自己的密码
     *
     * @param session
     * @param pwd
     * @return
     */
    @RequestMapping("/editCurrentUser")
    @ResponseBody
    public Json  editCurrentUser(User user){
        Json j = new Json();
        try {
            userService.edit(user);
            j.setSuccess(true);
            j.setMsg("编辑成功！");
            j.setObj(user);
        } catch (Exception e) {
            j.setMsg(e.getMessage());
        }
        return j;
    }
    /**
     * 跳转到当前修改界面的页面
     *
     * @param session
     *
     * @return
     */
    @RequestMapping("/editCurrentPage")
    public String editPage(String id, HttpServletRequest request) {
        User u = userService.get(id);
        request.setAttribute("user", u);
        return "/user/userEdit";
    }
    /**
     * 修改自己的密码
     *
     * @param session
     * @param pwd
     * @return
     */
    @RequestMapping("/editCurrentUserPwd")
    @ResponseBody
    public String editCurrentUserPwd(HttpSession session, String oldPwd, String pwd,HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        if (session != null) {
            SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
            if (sessionInfo != null) {
                if (userService.editCurrentUserPwd(sessionInfo, oldPwd, pwd)) {
                    jsobj.put("status", "1");
                    jsobj.put("msg", "修改成功,下次登录成功");
                } else {
                    jsobj.put("status", "0");
                    jsobj.put("msg", "修改失败");
                }
            } else {
                jsobj.put("status", "0");
                jsobj.put("msg", "登录超时");
            }
        } else {
            jsobj.put("status", "0");
            jsobj.put("msg", "登录超时");
        }
        return jsobj.toJSONString();
    }

    /**
     * 跳转到显示用户角色页面
     *
     * @return
     */
    @RequestMapping("/currentUserRolePage")
    public String currentUserRolePage(HttpServletRequest request, HttpSession session) {
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        request.setAttribute("userRoles", JSON.toJSONString(roleService.tree(sessionInfo)));
        return "/user/userRole";
    }

    /**
     * 跳转到显示用户权限页面
     *
     * @return
     */
    @RequestMapping("/currentUserResourcePage")
    public String currentUserResourcePage(HttpServletRequest request, HttpSession session) {
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        request.setAttribute("userResources", JSON.toJSONString(resourceService.allTree(sessionInfo)));
        return "/user/userResource";
    }

    /**
     * 用户登录时的autocomplete
     *
     * @param q
     *            参数
     * @return
     */
    @RequestMapping("/loginCombobox")
    @ResponseBody
    public List<User> loginCombobox(String q) {
        return userService.loginCombobox(q);
    }

    /**
     * 用户登录时的combogrid
     *
     * @param q
     * @param ph
     * @return
     */
    @RequestMapping("/loginCombogrid")
    @ResponseBody
    public DataGrid loginCombogrid(String q, PageHelper ph) {
        return userService.loginCombogrid(q, ph);
    }
    /**
     * 用户查询
     *
     * @param
     *
     */
    @RequestMapping("/querycurrentuser")
    @ResponseBody
    public String queryuser(HttpSession session,HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        if(sessionInfo != null){
            User u = userService.get(sessionInfo.getId());
            jsobj.put("status", "1");
            jsobj.put("msg", u);
        }else{
            jsobj.put("status", "0");
            jsobj.put("msg", "您还未登录!");
        }
        return jsobj.toJSONString();
    }


    /**
     * 用户查询备份
     *
     * @param
     *
     */
    @RequestMapping("/queryown")
    @ResponseBody
    public String queryown(HttpSession session,HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
        if(sessionInfo != null){
            User u = userService.get(sessionInfo.getId());
            jsobj.put("status", "1");
            jsobj.put("msg", u);
        }else{
            jsobj.put("status", "0");
            jsobj.put("msg", "您还未登录!");
        }
        return jsobj.toJSONString();
    }

    /**
     * 用户查询找密码
     *
     * @param User
     * @return
     */
    @RequestMapping("/findpassword")
    @ResponseBody
    public String  findpassword(User user,HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        String password = userService.getpwd(user);
        if("fail".equals(password)){
            jsobj.put("status", "0");
            jsobj.put("msg", "未查询到该密码");
        }else{
            jsobj.put("status", "1");
            jsobj.put("msg", password);
        }
        return jsobj.toJSONString();
    }
    /**
     * 用户忠诚榜
     *
     * @param q
     * @param ph
     * @return
     */
    @RequestMapping("/fealtyrank")
    @ResponseBody
    public String fealtyrank(HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        List<User> tuser =	userService.fealtyrank();
        if(tuser.size()>0){
            jsobj.put("status", "1");
            jsobj.put("msg", tuser);
        }else{
            jsobj.put("status", "1");
            jsobj.put("msg", tuser);
        }
        return jsobj.toJSONString();
    }

    /**
     * 用户富豪榜
     *
     * @param q
     * @param ph
     * @return
     */
    @RequestMapping("/regalrank")
    @ResponseBody
    public String regalrank(HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        List<User> tuser =	userService.regalrank();
        if(tuser.size()>0){
            jsobj.put("status", "1");
            jsobj.put("msg", tuser);
        }else{
            jsobj.put("status", "1");
            jsobj.put("msg",tuser);
        }
        return jsobj.toJSONString();

    }

    /**
     * 精英诚榜
     *
     * @param q
     * @param ph
     * @return
     */
    @RequestMapping("/outstandrank")
    @ResponseBody
    public String outstandrank(HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        List<User> tuser =	userService.outstandrank();
        if(tuser.size()>0){
            jsobj.put("status", "1");
            jsobj.put("msg", tuser);
        }else{
            jsobj.put("status", "1");
            jsobj.put("msg", "未查询到信息");
        }
        return jsobj.toJSONString();
    }

    /**
     * 大神周榜
     *
     * @param q
     * @param ph
     * @return
     */
    @RequestMapping("/weekrank")
    @ResponseBody
    public String weekrank(HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        JSONObject jsobj = new JSONObject();
        List<User> tuser =	userService.weekrank();
        if(tuser.size()>0){
            jsobj.put("status", "1");
            jsobj.put("msg", tuser);
        }else{
            jsobj.put("status", "1");
            jsobj.put("msg", tuser);
        }
        return jsobj.toJSONString();
    }

    //更新任务次数
    public void updatetaskcount(String id){
        User user = new User();
        User u = userService.get(id);
        user.setId(id);
        user.setTaskcount(u.getTaskcount()+1);//任务次数加1
        try {
            userService.edittaskcount(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //升级会员标识
    public void updatelevl(String id,Integer levl){
        User u = userService.get(id);
        u.setId(id);
        u.setLevl(levl);//任务次数加1
        try {
            userService.editlevl(u);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //增加完善资料用户信息
    public void addtaskrecord(Long userid){
        Mtaskrecord  task = new Mtaskrecord();
        task.setTaskType("2");		//设置类型
        task.setUserid(userid);		//设置用户id
        try {
            Integer score = taskTypeService.gettasktype("2").getScore();
            task.setScore(score);		//设置积分
            taskrecordService.add(task);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新上线人总积分
    @RequestMapping("/updateuserscore")
    @ResponseBody
    public void updateuserscore(HttpServletRequest request){
        //上线人id
        String userid=request.getParameter("userid");
        String score=request.getParameter("score");
        System.out.print("userid------------------------------------->"+userid);

        Tuser user=userService.getUserByUserId(userid);
        User u=new User();
        BeanUtils.copyProperties(user, u);
        try {
            if(user!=null){
                u.setTotalscore(user.getTotalscore()+Integer.parseInt(score));
                u.setInvitecount(user.getInvitecount()+1);
                u.setScorefrominvite(user.getScorefrominvite()+Integer.parseInt(score));
                u.setUnchangedscore(user.getUnchangedscore()+Integer.parseInt(score));
                userService.editinvitescore(u);
            }

        }catch (Exception e){
        }
    }

    //更新总积分
    public void updatetotalscore(String id,Integer score,int type){
        User user = new User();
        User u = userService.get(id);
        user.setId(id);
        user.setTaskcount(u.getTaskcount()+1);//任务次数加1
        try {
            if(type == 1){						  //表示加总积分涉及可用积分
                user.setTotalscore(u.getTotalscore()+score);
                user.setUnchangedscore(u.getUnchangedscore()+score);
                userService.editotlescore(user);
            }else if(type == 2){				  //表示兑换总积分与可用积分的变化
                user.setTotalscore(u.getTotalscore()-score);
                user.setUnchangedscore(u.getUnchangedscore()-score);
                user.setChangedscore(score);
                user.setChangedcount(u.getChangedcount()+1);
                userService.editexchangescore(user);
            }else if(type == 3){			      //邀请人记录积分的变化
                user.setTotalscore(u.getTotalscore()+score);
                user.setInvitecount(u.getInvitecount()+1);
                user.setScorefrominvite(u.getScorefrominvite()+score);
                user.setUnchangedscore(u.getUnchangedscore()+score);
                userService.editinvitescore(user);
            }else if(type == 4){
                user.setTotalscore(u.getTotalscore()-score);
                user.setUnchangedscore(u.getUnchangedscore()-score);
                userService.editrockscore(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
